var gulp = require('gulp')
var del = require('del')
var rename = require('gulp-rename')
var concat = require('gulp-concat')
var postcss = require('gulp-postcss')
var cleanCss = require('gulp-clean-css')
var requirejs = require('requirejs')
var uglify = require('gulp-uglify')
var rev = require('gulp-rev')

// Clean task, delete all pre build files and directories
gulp.task('clean', function(cb) {
  return del([
    '.temp/**',
    'webapp/resource/build',
    'src/main/resources/assets.json'
  ], cb)
})

// Image task
gulp.task('image', function() {
  return gulp.src([
    'webapp/resource/image/**',
    'webapp/resource/img/**'
  ], { base: 'webapp/resource/' })
  .pipe(gulp.dest('webapp/resource/build/'))
})

// Style task
gulp.task('style', function() {
  return gulp.src([
      'webapp/resource/css/sm.css',
      'webapp/resource/css/sm.hack.css',
      'webapp/resource/css/app.css'
    ])
    .pipe(concat('app.css'))
    .pipe(postcss([
      require('css-mqpacker'),
      require('autoprefixer')({
        browsers: ['> 0.1%', 'Android >= 4.1', 'iOS > 6', 'Chrome >= 30', 'Safari > 6.0'],
        flexbox: true
      }),
      require('cssnano')
      // require('postcss-assets')({
      //   loadPaths: [
      //     'webapp/resource/css/img/',
      //     'webapp/resource/css/fonts/',
      //     'webapp/resource/image/'
      //   ]
      // })
    ]))
    .pipe(gulp.dest('.temp/css'))
    .pipe(cleanCss({
      keepSpecialComments: 0
    }))
})

var path = require('path')
var fs = require('fs')
var PAGE_PATH = path.join(__dirname, 'webapp/resource/js/page')
var SCRIPT_PATH = path.join(__dirname, 'webapp/resource/js')

function readScripts(directory) {
  var scripts = []
  var dirs = fs.readdirSync(directory)
    .forEach(function(dir) {
      var currentPath = path.resolve(directory, dir)
      if (fs.statSync(currentPath).isDirectory()) {
        scripts = scripts.concat(readScripts(currentPath))
      } else {
        scripts.push(currentPath)
      }
    })
  return scripts
}

var scriptModules = [{
      name: 'build',
      include: [
        'requireLib',
        'zepto',
        'underscore',
        'sui',
        'utils'
      ]
    }]
    .concat(
      readScripts(PAGE_PATH).map(function(item) {
        var extname = path.extname(item)
        var relativePath = item.slice(SCRIPT_PATH.length + 1, -(extname.length))
        return {
          name: relativePath,
          exclude: ['build']
        }
      })
    )

// Script task, requirejs optimize
gulp.task('script', function(cb) {
  requirejs.optimize({
    appDir: 'webapp/resource/js',
    mainConfigFile: 'webapp/resource/js/build.js',
    dir: '.temp/js',
    findNestedDependencies: true,
    // optimize: 'none',
    modules: scriptModules
  }, function(buildResponse) {
    cb()
  }, cb)
})

// Build task, add reversion for scripts and style sheets
gulp.task('build', ['image', 'style', 'script'], function() {
  return gulp.src([
      '.temp/**/*.css',
      '.temp/**/*.js',
    ], { base: '.temp' })
    .pipe(rev())
    .pipe(gulp.dest('webapp/resource/build'))
    .pipe(rev.manifest('assets.json', {
      merge: true
    }))
    .pipe(gulp.dest('src/main/resources'))
})

// Default task
gulp.task('default', ['clean'], function() {
  gulp.start('build')
})